<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.zy.entity.User" %>
<%@ page import="java.util.List" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
    int currentPage = 1;  // 将变量名改为 currentPage
    if (request.getParameter("page") != null) {
        try {
            currentPage = Integer.parseInt(request.getParameter("page"));
        } catch (NumberFormatException e) {
            currentPage = 1; // 如果解析失败，默认设置为第一页
        }
    }
%>
<html>

<head>
    <title>管理员页面</title>
    <script>
        // 页面加载时执行
        window.onload = function () {
            // 默认显示用户管理界面
            showSection('userManagement');
            // 获取用户列表
            loadUsers();
            // 获取商品列表
            loadShops();
        };

        // 显示指定部分
        function showSection(sectionId) {
            var sections = document.querySelectorAll('.section');
            sections.forEach(function (section) {
                section.style.display = 'none'; // 隐藏所有部分
            });
            document.getElementById(sectionId).style.display = 'block'; // 显示指定部分

            // 更新菜单项的活动状态
            var links = document.querySelectorAll('.sidebar a');
            links.forEach(function (link) {
                link.classList.remove('active'); // 移除所有链接的活动状态
            });
            document.querySelector(`.sidebar a[onclick="showSection('${sectionId}')"]`).classList.add('active'); // 添加活动状态
        }

        // 加载用户列表
        function loadUsers(page = 1) {
            fetch('/untitled_war_exploded/getUsers')
                .then(response => response.json())
                .then(users => {
                    renderUserTable(users, page);
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert("获取用户列表失败");
                });
        }

        // 渲染用户表格
        function renderUserTable(users, page) {
            const userTable = document.getElementById('userTable');
            const pageSize = 5; // 每页显示的用户数量
            const totalPages = Math.ceil(users.length / pageSize);
            const start = (page - 1) * pageSize;
            const end = start + pageSize;
            const currentPageUsers = users.slice(start, end);

            let tableHtml = `
                <table>
                    <tr>
                        <th>用户名</th>
                        <th>密码</th>
                        <th>角色</th>
                        <th>余额</th>
                        <th>操作</th>
                    </tr>`;

            currentPageUsers.forEach(user => {
                const roleName = user.userType === 0 ? "管理员" : "普通用户";
                tableHtml += `
                    <tr>
                        <td>${user.username}</td>
                        <td>${user.password}</td>
                        <td>${roleName}</td>
                        <td>${user.balance}</td>
                        <td>
                            <button onclick="showEditUserModal('${user.username}', '${user.password}', ${user.userType}, ${user.balance})">
                                编辑
                            </button>
                            <button onclick="deleteUser('${user.username}')">
                                删除
                            </button>
                        </td>
                    </tr>`;
            });

            tableHtml += '</table>';

            // 添加分页控件
            tableHtml += `
                <div class="pagination">
                    <c:if test="${page > 1}">
                        <button onclick="loadUsers(${page - 1})">上一页</button>
                    </c:if>
                    <span>第 ${page} 页，共 ${totalPages} 页</span>
                    <c:if test="${page < totalPages}">
                        <button onclick="loadUsers(${page + 1})">下一页</button>
                    </c:if>
                </div>`;

            userTable.innerHTML = tableHtml;
        }

        // 查找用户
        function searchUser() {
            const name = document.getElementById('searchName').value;
            fetch(`/untitled_war_exploded/findUserByName?name=${name}`)
                .then(response => response.json())
                .then(data => {
                    renderUserTable(data, 1); // 使用渲染函数显示查找结果，重置为第一页
                })
                .catch(error => console.error('Error:', error));
        }

        // 显示添加用户的模态框
        function showAddUserModal() {
            document.getElementById('addUserModal').style.display = 'block'; // 显示模态框
        }

        // 关闭模态框
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none'; // 隐藏模态框
        }

        // 提交新增用户表单
        function submitAddUser() {

            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const role = document.getElementById('role').value;
            const balance = document.getElementById('balance').value;
            const url = new URL('http://localhost:8080/untitled_war_exploded/addUser');
            url.searchParams.append('username', username);
            url.searchParams.append('password', password);
            url.searchParams.append('role', role);
            url.searchParams.append('balance', balance);

            fetch(url, {
                method: 'POST' // 使用 GET 方法
            })
                .then(response => {
                    if (response.ok) {
                        return response.text(); // 读取响应文本
                    } else {
                        throw new Error('添加用户失败，请重试。');
                    }
                })
                .then(data => {
                    console.log('Success:', data);
                    loadUsers(); // 重新加载用户列表
                    closeModal('addUserModal'); // 关闭模态框
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert(error.message);
                });
        }

        // 加载商品列表
        function loadShops(page = 1) {
            fetch(`/untitled_war_exploded/getShops?page=${page}`)
                .then(response => response.json())
                .then(data => {
                    renderShopTable(data.shops, page, data.totalShops);
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert("获取商品列表失败");
                });
        }

        // 渲染商品表格
        function renderShopTable(shops, page, totalShops) {
            const shopTable = document.getElementById('shopTable');
            const pageSize = 5; // 每页显示的商品数量
            const totalPages = Math.ceil(totalShops / pageSize);
            const start = (page - 1) * pageSize;
            const end = start + pageSize;
            const currentPageShops = shops;

            let tableHtml = `
                            <table>
                                <tr>
                                    <th>商品名称</th>
                                    <th>图片</th>
                                    <th>价格</th>
                                    <th>联系人</th>
                                    <th>联系电话</th>
                                </tr>`;

            currentPageShops.forEach(shop => {
                tableHtml += `
                                <tr>
                                    <td>${shop.name}</td>
                                    <td><img src="${shop.url}" alt="${shop.name}" style="width:50px;height:50px;"></td>
                                    <td>${shop.price}</td>
                                    <td>${shop.contactPerson}</td>
                                    <td>${shop.contactPhone}</td>
                                </tr>`;
            });

            tableHtml += '</table>';

            // 添加分页控件
            tableHtml += `
                            <div class="pagination">
                                <c:if test="${page > 1}">
                                    <button onclick="loadShops(${page - 1})">上一页</button>
                                </c:if>
                                <span>第 ${page} 页，共 ${totalPages} 页</span>
                                <c:if test="${page < totalPages}">
                                    <button onclick="loadShops(${page + 1})">下一页</button>
                                </c:if>
                            </div>`;

            shopTable.innerHTML = tableHtml;
        }

        // 查找商品
        function searchShops() {
            const name = document.getElementById('searchShopName').value;
            fetch(`/untitled_war_exploded/findShopByName?name=${name}`)
                .then(response => response.json())
                .then(data => {
                    renderShopTable(data);
                })
                .catch(error => console.error('Error:', error));
        }

        // 显示添加商品的模态框
        function showAddShopModal() {
            document.getElementById('addShopModal').style.display = 'block'; // 显示模态框
        }

        // 提交新增商品表单
        function submitAddShop() {
            const shopName = document.getElementById('shopName').value;
            const shopPrice = document.getElementById('shopPrice').value;
            const shopContactPerson = document.getElementById('shopContactPerson').value;
            const shopContactPhone = document.getElementById('shopContactPhone').value;
            const url = new URL('http://localhost:8080/untitled_war_exploded/addShop');
            url.searchParams.append('shopName', shopName);
            url.searchParams.append('shopPrice', shopPrice);
            url.searchParams.append('shopContactPerson', shopContactPerson);
            url.searchParams.append('shopContactPhone', shopContactPhone);

            fetch(url, {
                method: 'POST'
            })
                .then(response => {
                    if (response.ok) {
                        alert('商品添加成功');
                        return response.text();
                    } else {
                        throw new Error('添加商品失败，请重试。');
                    }
                })
                .then(data => {
                    console.log('Success:', data);
                    loadShops(); // 重新加载商品列表
                    closeModal('addShopModal'); // 关闭模态框
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert(error.message);
                });
        }
    </script>
    <style>
        /* 页面整体样式 */
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
        }

        /* 侧边栏样式 */
        .sidebar {
            width: 200px;
            background-color: #2c3e50;
            color: white;
            padding: 20px;
            min-height: 100vh;
            box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
        }

        .sidebar h2 {
            color: #fff;
            margin-bottom: 30px;
            font-size: 24px;
            text-align: center;
            padding-bottom: 15px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .sidebar a {
            display: block;
            color: #ecf0f1;
            padding: 12px 15px;
            margin: 8px 0;
            text-decoration: none;
            border-radius: 5px;
            transition: all 0.3s ease;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .sidebar a:hover {
            background-color: #34495e;
            transform: translateX(5px);
        }

        .sidebar a.active {
            background-color: #3498db;
        }

        .sidebar svg {
            width: 20px;
            height: 20px;
            fill: currentColor;
        }

        /* 按钮样式 */
        button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 3px;
            cursor: pointer;
            margin-right: 5px;
            display: inline-flex;
            align-items: center;
        }

        button svg {
            margin-right: 5px;
        }

        button:hover {
            background-color: #2980b9;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal-content {
            background-color: white;
            margin: 15% auto;
            padding: 20px;
            width: 70%;
            max-width: 500px;
            border-radius: 5px;
        }

        .close {
            float: right;
            cursor: pointer;
            font-size: 20px;
        }

        /* 表单样式 */
        form input,
        form select {
            width: 100%;
            padding: 8px;
            margin: 8px 0;
            box-sizing: border-box;
        }

        /* 分页控件样式 */
        .pagination {
            margin-top: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
        }

        .pagination button {
            padding: 5px 15px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }

        .pagination button:hover {
            background-color: #2980b9;
        }

        .pagination span {
            color: #666;
        }

        /* 主容器样式 */
        .container {
            flex: 1;
            padding: 20px;
            background-color: #f5f7fa;
            overflow-y: auto;
        }

        /* 表格样式 */
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            background-color: white;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            border-radius: 4px;
        }

        th,
        td {
            border: 1px solid #eee;
            padding: 12px;
            text-align: left;
        }

        th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #2c3e50;
        }

        tr:hover {
            background-color: #f8f9fa;
        }

        /* 添加用户按钮样式 */
        .add-user-btn {
            background-color: #27ae60;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 5px;
            margin-bottom: 20px;
        }

        .add-user-btn:hover {
            background-color: #219a52;
        }

        .add-user-btn svg {
            width: 20px;
            height: 20px;
        }
    </style>
</head>

<body>
<!-- 侧边栏导航 -->
<div class="sidebar">
    <h2>管理面板</h2>
    <a onclick="showSection('userManagement')" class="active">
        <svg viewBox="0 0 24 24">
            <path
                    d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" />
        </svg>
        用户管理
    </a>
    <a onclick="showSection('shopManagement')">
        <svg viewBox="0 0 24 24">
            <path
                    d="M7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zM1 2v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.14 0-.25-.11-.25-.25l.03-.12.9-1.63h7.45c.75 0 1.41-.41 1.75-1.03l3.58-6.49c.08-.14.12-.31.12-.48 0-.55-.45-1-1-1H5.21l-.94-2H1zm16 16c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2z" />
        </svg>
        商品管理
    </a>
    <a onclick="showSection('orderManagement')">
        <svg viewBox="0 0 24 24">
            <path
                    d="M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm2 14H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z" />
        </svg>
        订单管理
    </a>
    <a onclick="showSection('statisticsManagement')">
        <svg viewBox="0 0 24 24">
            <path
                    d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z" />
        </svg>
        统计分析
    </a>
    <a href="index.jsp">
        <svg viewBox="0 0 24 24">
            <path
                    d="M10.09 15.59L11.5 17l5-5-5-5-1.41 1.41L12.67 11H3v2h9.67l-2.58 2.59zM19 3H5c-1.11 0-2 .9-2 2v4h2V5h14v14H5v-4H3v4c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z" />
        </svg>
        返回首页
    </a>
    <button class="cart-btn" onclick="window.location.href='car.jsp'">
        <svg width="16" height="16" fill="currentColor" class="bi bi-cart" viewBox="0 0 16 16">
            <path d="M0 1a1 1 0 0 1 1-1h1.5a1 1 0 0 1 .97.757L3.89 3H14a1 1 0 0 1 .98 1.197l-1.5 8A1 1 0 0 1 12.5 13H4a1 1 0 0 1-.98-.804L1.61 3.607 1.11 2H1a1 1 0 0 1-1-1zM4.5 4l1.5 8h7l1.5-8H4.5zM5 12a2 2 0 1 0 4 0 2 2 0 0 0-4 0zm6 0a2 2 0 1 0 4 0 2 2 0 0 0-4 0z"/>
        </svg>
        购物车
    </button>
</div>

<!-- 主内容区域 -->
<div class="container">
    <h1>管理员界面</h1>

    <!-- 用户管理部分 -->
    <div class="section" id="userManagement">
        <h2>管理用户</h2>
        <!-- 增加用户按钮 -->
        <button class="add-user-btn" onclick="showAddUserModal()">
            <svg width="16" height="16" fill="currentColor" class="bi bi-plus" viewBox="0 0 16 16">
                <path
                        d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z" />
            </svg>
            增加用户
        </button>
        <!-- 添加查找用户的输入框和按钮 -->
        <div>
            <input type="text" id="searchName" placeholder="输入姓名查找用户">
            <button onclick="searchUser()">查找用户</button>
        </div>
        <!-- 用户列表表格 -->
        <div id="userTable">
            <!-- 这里的内容会被AJAX加载数据替换 -->
        </div>
    </div>

    <!-- 商品管理部分 -->
    <div class="section" id="shopManagement" style="display: none;">
        <h2>管理商品</h2>
        <!-- 添加商品按钮 -->
        <button class="add-user-btn" onclick="showAddShopModal()">
            <svg width="16" height="16" fill="currentColor" class="bi bi-plus" viewBox="0 0 16 16">
                <path
                        d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z" />
            </svg>
            添加商品
        </button>
        <!-- 添加查找商品的输入框和按钮 -->
        <div>
            <input type="text" id="searchShopName" placeholder="输入商品名称查找">
            <button onclick="searchShops()">查找商品</button>
        </div>
        <!-- 商品列表表格 -->
        <div id="shopTable">
            <table>
                <tr>
                    <th>商品名称</th>
                    <th>图片</th>
                    <th>价格</th>
                    <th>联系人</th>
                    <th>联系电话</th>
                </tr>
                <!-- 商品数据将通过JavaScript动态填充 -->
            </table>
        </div>
    </div>
</div>

<!-- 添加用户模态框 -->
<div id="addUserModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeModal('addUserModal')">&times;</span>
        <h2>添加用户</h2>
        <form id="addUserForm">
            <input type="text" id="username" name="username" placeholder="用户名" required>
            <input type="password" id="password" name="password" placeholder="密码" required>
            <select id="role" name="role" required>
                <option value="0">管理员</option>
                <option value="1">普通用户</option>
            </select>
            <input type="number" id="balance" name="balance" placeholder="余额" step="0.01" required>
            <button type="button" onclick="submitAddUser()">添加</button>
            <button type="button" onclick="closeModal('addUserModal')">取消</button>
        </form>
    </div>
</div>
<!-- 添加商品模态框 -->
<div id="addShopModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeModal('addShopModal')">&times;</span>
        <h2>添加商品</h2>
        <form id="addShopForm">
            <input type="text" id="shopName" name="shopName" placeholder="商品名称" required>
            <input type="number" id="shopPrice" name="shopPrice" placeholder="价格" step="0.01" required>
            <input type="text" id="shopContactPerson" name="shopContactPerson" placeholder="联系人" required>
            <input type="text" id="shopContactPhone" name="shopContactPhone" placeholder="联系电话" required>
            <button type="button" onclick="submitAddShop()">添加</button>
            <button type="button" onclick="closeModal('addShopModal')">取消</button>
        </form>
    </div>
</div>
</body>

</html>